
<template>
  <div class="health-container">
    <!-- 导航栏 -->
    <header>
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <div class="container">
        <nav>
          <div class="logo">
            <a href="/">安心<span>陪诊</span></a>
          </div>
          <ul class="nav-links">
            <li><a href="/">首页</a></li>
            <li><a href="#" @click.prevent="goToServiceType">服务项目</a></li>
            <li><a href="#" @click.prevent="goToServiceProcess">服务流程</a></li>
            <li><a href="#" @click.prevent="goToNotice">公告中心</a></li>
            <li
                @mouseenter="showDropdown('about')"
                @mouseleave="hideDropdown()"
                @click.stop="toggleDropdown('about')"
            >
              <a href="#" @click.prevent>
                关于我们
                <el-icon><ArrowDown /></el-icon>
              </a>
              <ul
                  class="dropdown-menu"
                  v-if="activeDropdown === 'about'"
                  @mouseenter="cancelHide()"
                  @mouseleave="hideDropdown()"
              >
                <li><a href="#" @click="router.push('/about')">项目简介</a></li>
                <li><a href="#" @click="router.push('/contact')">联系我们</a></li>
              </ul>
            </li>
          </ul>
          <div class="nav-buttons">
            <button @click="goToLogin" class="btn">登录</button>
            <button @click="goToRegister" class="btn">注册</button>
          </div>
        </nav>
      </div>
    </header>

    <main class="main-content">
      <div class="login-container">
        <div class="login-section">
          <h2>登录</h2>
          <form @submit.prevent="login" class="login-form">
            <div class="form-group">
              <select v-model="loginForm.role" class="role-select">
                <option value="user">用户</option>
                <option value="escort">陪诊人员</option>
                <option value="manager">管理员</option>
              </select>
            </div>
            <div class="form-group">
              <input
                  type="text"
                  v-model="loginForm.username"
                  placeholder="输入用户名/手机号"
                  required
              >
            </div>
            <div class="form-group">
              <input
                  type="password"
                  v-model="loginForm.password"
                  placeholder="输入密码"
                  required
              >
            </div>
            <button type="submit" class="submit-btn">登录</button>
          </form>
        </div>
      </div>
    </main>

    <!-- 页脚 -->
    <footer>
      <div class="container">
        <div class="footer-content">
          <div class="footer-section">
            <h3>关于我们</h3>
            <p>安心陪诊致力于为需要就医陪伴的用户提供专业、贴心的陪诊服务。</p>
          </div>
          <div class="footer-section">
            <h3>快速链接</h3>
            <ul>
              <li><a href="/">首页</a></li>
              <li><a href="/about">关于我们</a></li>
              <li><a href="/contact">联系我们</a></li>
              <li><a href="#" @click.prevent="goToUserAgreement">用户协议</a></li>
              <li><a href="#" @click.prevent="goToPrivacyPolicy">隐私政策</a></li>
            </ul>
          </div>
          <div class="footer-section">
            <h3>联系我们</h3>
            <p>电话：400-123-4567</p>
            <p>邮箱：service@anxinpeizhen.com</p>
          </div>
        </div>
        <div class="copyright">
          <p>&copy; 2025 安心陪诊平台 版权所有</p>
        </div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import {ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter();

axios.defaults.withCredentials = true; // ✅ 全局设置，允许跨域携带 Cookie

const loginForm = ref({
  role: 'user', // 默认用户角色
  username: '',
  password: ''
});

const activeDropdown = ref(null);
const hoverTimeout = ref(null);

const dropdownOptions = {
  'escort': [
    { name: '陪诊师列表', path: '/escort/list' },
    { name: '陪诊师认证', path: '/escort/certification' }
  ],
  'about': [
    { name: '项目简介', path: '/about' },
    { name: '联系我们', path: '/contact' }
  ]
};

const showDropdown = (menu) => {
  clearTimeout(hoverTimeout.value);
  activeDropdown.value = menu;
};

const hideDropdown = () => {
  hoverTimeout.value = setTimeout(() => {
    activeDropdown.value = null;
  }, 200);
};

const cancelHide = () => {
  clearTimeout(hoverTimeout.value);
};

const toggleDropdown = (menu) => {
  activeDropdown.value = activeDropdown.value === menu ? null : menu;
};

// 判断输入的是手机号还是用户名
const isPhoneNumber = (input) => {
  return /^1[3-9]\d{9}$/.test(input); // 简单的手机号验证
};

const login = async () => {
  try {
    // 根据角色选择不同的登录接口
    let endpoint = '';
    switch (loginForm.value.role) {
      case 'user':
        endpoint = '/v1/user/login';
        break;
      case 'escort':
        endpoint = '/v1/escort/login';
        break;
      case 'manager':
        endpoint = '/v1/manager/login';
        break;
    }

    // 构建请求参数
    const requestData = {
      password: loginForm.value.password
    };

    // 根据输入判断是手机号还是用户名
    if (isPhoneNumber(loginForm.value.username)) {
      requestData.phone = loginForm.value.username;
    } else {
      requestData.username = loginForm.value.username;
    }

    const response = await axios.post(BASE_URL + `${endpoint}`, requestData, {
      withCredentials: true // 确保发送和接收 cookies
    });

    if (response.data.state === 2000) {
      ElMessage.success('登录成功!');
      console.log(response.data.data);

      // 根据角色存储信息（管理员专用）
      if (loginForm.value.role === 'manager') {
        localStorage.setItem('managerInfo', JSON.stringify(response.data.data));
        localStorage.setItem('managerToken', response.data.data.token); // 明确存储为 managerToken
      }
      if (loginForm.value.role === 'user') {
        localStorage.setItem('user', JSON.stringify(response.data.data));
      }else {
        // 其他角色（用户、陪护等）的存储逻辑
        localStorage.setItem('user', JSON.stringify(response.data.data));
        localStorage.setItem('token', response.data.data.token);
      }

      // 保存 session token 到本地存储（如果响应中包含）
      if (response.data.data.token) {
        localStorage.setItem('token', response.data.data.token);
      }

      // 设置 axios 默认请求头，包含认证信息
      if (response.data.data.token) {
        axios.defaults.headers.common['Authorization'] = `Bearer ${response.data.data.token}`;
      }

      // 设置 axios 默认 withCredentials 为 true，确保后续请求携带 cookies
      axios.defaults.withCredentials = true;

      // 根据角色跳转到不同页面
      switch (loginForm.value.role) {
        case 'user':
          router.push('/user/first');
          break;
        case 'escort':
          router.push('/escorthome');
          break;
        case 'manager':
          router.push('/managerPersonal');
          break;
      }
    } else {
      ElMessage.error(response.data.message);
      loginForm.value.password = '';
    }
  } catch (error) {
    console.error('登录出错:', error);
    ElMessage.error(error.response?.data?.message || '请检查用户名/手机号和密码');
    loginForm.value.password = '';
  }
};

const goToRegister = () => {
  router.push('/register');
};

const goToNotice = () => {
  router.push('/notice');
};

const goToUserAgreement = () => {
  router.push('/userAgreement')
};

const goToPrivacyPolicy = () => {
  router.push('/privacyPolicy')
};

const goToServiceProcess = () => {
  router.push('/serviceProcess')
}

const goToServiceType = () => {
  router.push('/serviceType')
}

</script>

<style scoped>
/* 新增的样式 */
.health-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.main-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.login-container {
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
}

/* 修改原有的登录部分样式 */
.login-section {
  background: white;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.login-section h2 {
  font-size: 24px;
  margin-bottom: 30px;
  color: #2c3e50;
  text-align: center;
}

/* 保持其他原有样式不变 */
.dropdown-arrow svg {
  width: 1em;
  height: 1em;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

body {
  background-color: #f5f7fa;
  color: #333;
  line-height: 1.6;
}

a {
  text-decoration: none;
  color: inherit;
}

ul {
  list-style: none;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 15px;
}

.btn {
  display: inline-block;
  padding: 10px 20px;
  background-color: #4a90e2;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
  border: none;
  font-size: 16px;
}

.btn:hover {
  background-color: #3a7bc8;
}

.btn-secondary {
  background-color: #6c757d;
}

.btn-secondary:hover {
  background-color: #5a6268;
}

/* 导航栏 */
header {
  background-color: white;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
}

nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
}

.logo {
  font-size: 24px;
  font-weight: bold;
  color: #4a90e2;
}

.logo span {
  color: #333;
}

.nav-links {
  display: flex;
  gap: 30px;
}

.nav-links a {
  font-weight: 500;
  transition: color 0.3s;
}

.nav-links a:hover {
  color: #4a90e2;
}

.nav-buttons {
  display: flex;
  gap: 15px;
}
.auth-buttons button {
  padding: 8px 20px;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.login-btn {
  background-color: transparent;
  border: 1px solid #4a90e2;
  color: #4a90e2;
}

.login-btn:hover {
  background-color: #4a90e2;
  color: white;
}

.register-btn {
  background-color: #4a90e2;
  border: 1px solid #4a90e2;
  color: white;
}

.register-btn:hover {
  background-color: #3a7bc8;
  border-color: #3a7bc8;
}

.login-form {
  width: 100%;
}

.form-group {
  margin-bottom: 20px;
  width: 100%;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  box-sizing: border-box;
}

.role-select {
  appearance: none;
  background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right 1px center;
  background-size: 1em;
}

.submit-btn {
  background-color: #4a90e2;
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
  width: 100%;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #3a7bc8;
}

/* 页脚 */
footer {
  background-color: #2c3e50;
  color: #fff;
  padding: 60px 0 20px;
}

.footer-content {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 40px;
  margin-bottom: 40px;
}

.footer-section h3 {
  font-size: 18px;
  margin-bottom: 20px;
  color: #fff;
}

.footer-section p {
  margin-bottom: 15px;
  color: #bbb;
}

.footer-section ul li {
  margin-bottom: 10px;
}

.footer-section a {
  color: #bbb;
  transition: color 0.3s;
}

.footer-section a:hover {
  color: #4a90e2;
}

.copyright {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #3d5166;
  color: #bbb;
}

/* 下拉菜单样式 */
.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background-color: white;
  min-width: 160px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 10px 0;
  z-index: 1000;
}

.dropdown-menu li {
  padding: 8px 20px;
  transition: background-color 0.3s;
}

.dropdown-menu li:hover {
  background-color: #f5f7fa;
}

.dropdown-menu a {
  display: block;
  color: #333;
  white-space: nowrap;
}

.dropdown-menu a:hover {
  color: #4a90e2;
}

.nav-links > li {
  position: relative;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .nav-links {
    display: none;
  }

  .terms-container {
    padding: 20px;
  }

  .terms-container h1 {
    font-size: 26px;
  }

  .footer-content {
    grid-template-columns: 1fr;
  }

  .login-section {
    padding: 30px 20px;
  }
}
</style>